﻿using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPITest.Models.Database;

namespace WebAPITest.service
{
    public class RedisService:IRedisService
    {
        private readonly IDatabase _redis;
        public RedisService(RedisHelper client)
        {
            _redis = client.GetDatabase();
        }
        /// <summary>
        /// 添加商品浏览记录
        /// </summary>
        public void AddGoodViews(int userId,Good good)
        {
            var key = $"UserViews{{userId}}";
            //取之前的浏览记录
            //在用户浏览商品的时候 添加商品浏览记录 商品
            //新数据在左边还是右边
            //最近浏览的商品
            //新 旧
            //浏览商品的时间戳
            //var score = 0;
            var jsonStr = JsonConvert.SerializeObject(good);//序列化
            _redis.ListLeftPush(key, jsonStr);
        }
        /// <summary>
        /// 查询用户的商品浏览记录
        /// </summary>
        /// <param name="userId"></param>
        public List<Good> GetUserView(int userId)
        {
            var key = $"UserViews{{userId}}";
            //取之前的浏览记录
            var cache = _redis.ListRange(key,0,4);

            //浏览商品记录
            var views = new List<Good>();
            foreach(var item in cache)
            {
                var good = JsonConvert.DeserializeObject<Good>(item);
            }
            return views;
        }
    }
}
